<template>
  <view class="box" :class="['qn-page-' + theme]">
    <view class="top-bg"></view>
    <view class="welcome-title">
      <view>嗨～朋友</view>
      <view>欢迎使用</view>
    </view>
    <view class="logo-img">
      <image
        :src="imgHost + '/statics/logo1024-fff.png'"
        mode="aspectFill"
      ></image>
    </view>
    <view class="login-bg" v-if="login_type === 1">
      <image
        :src="imgHost + '/statics/login-img.jpg'"
        mode="aspectFill"
      ></image>
      <view class="login-btn-view">
        <!-- #ifdef APP-PLUS || MP-WEIXIN -->
        <view class="wx-Btn" @click="WXLogin">微信授权快速登录</view>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view class="wx-Btn" @click="H5WXLogin">微信授权快速登录</view>
        <!-- #endif -->
        <!-- 		<view class="yzm-Btn" @click="login_type = 2">
					<text class="ibonfont ibonshouji1"></text>
					短信验证登录
				</view> -->
      </view>
    </view>
    <view class="login-bg" v-if="login_type === 2">
      <view class="tab-ul">
        <view class="tab-li" @click="login_type = 1">微信快捷登录</view>
        <view class="tab-on">手机验证登录</view>
      </view>
      <view class="input-ul">
        <view class="input-li">
          <text class="ibonfont ibonshouji1"></text>
          <input
            type="number"
            placeholder-class="input-pl"
            v-model="mobile"
            placeholder="请输入手机号"
          />
        </view>
        <view class="input-li">
          <text class="ibonfont ibonyanzhengma"></text>
          <input
            type="number"
            placeholder-class="input-pl"
            v-model="smsCode"
            placeholder="请输入验证码"
          />
          <view class="yzm-view">获取验证码</view>
        </view>
      </view>
      <view class="login-btn">登录</view>
      <u-divider half-width="280" border-color="#eeeeee" color="#CAD0D7"
        ><text class="divider-text">or</text>
      </u-divider>
      <view class="wx-change-btn" @click="login_type = 1">
        <u-icon
          class="wxicon"
          name="weixin-fill"
          color="#28c422"
          size="40"
        ></u-icon>
        微信登录
      </view>
    </view>
  </view>
</template>

<script>
import webUrl from '@/config.js';
export default {
  data() {
    return {
      imgHost : webUrl.QN_URL,
      userInfo: {},
      base_set_info: {},
      login_type: 1,
      mobile: "",
      smsCode: "",
      source: 2,
      is_dis_yzm: false,
      num: 60,
      unionId: "",
      openId: "",
      isIosLogin: true,
    };
  },
  onShow() {
    // #ifdef MP
    uni.hideHomeButton();
    // #endif
  },
  onLoad(options) {
    // #ifdef H5
    const codeindex = location.href.indexOf("code=") + 5;
    const stateindex = location.href.indexOf("&state");
    const code = location.href.substring(codeindex, stateindex);
    if (stateindex > -1) {
      this.getAccessToken(code);
    }
    // #endif
    if (options.loginType) {
      this.login_type = parseInt(options.loginType);
    }

    this.base_set_info = this.$store.state.baseSet;

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    if (res.platform === "ios") {
      const iosAuditStatus = this.$store.state.iosAuditStatus;
      if (iosAuditStatus === 4) {
        this.goPage("/pagesT/public/login");
        this.isIosLogin = false;
      } else {
        this.isIosLogin = true;
      }
    }
    // #endif
  },
  methods: {
    //H5 获取accessToken
    getAccessToken(code) {
      this.$u.api
        .getAccessToken({
          code: code,
          type: 1,
        })
        .then((res) => {
          uni.setStorageSync("openid", res.data.openid);
          uni.setStorageSync("unionid", res.data.unionid);
          this.unionIDUserinfo(res.data.access_token, res.data.openid);
        });
    },
    mobileInput(e) {
      let val = e.detail.value;
      if (val.length === 3 || val.length === 8) {
        val += " ";
      }
      this.$nextTick(() => {
        this.mobile = val;
      });
    },
    closePage() {
      if (!this.isIosLogin) {
        uni.navigateBack();
      } else {
        this.goPage("/pages/index/index", "switchTab");
      }
    },
    // 验证码
    getYzm() {
      const mobile = this.$_utils.mobileRe(this.mobile);
      const re = /^1[3456789]\d{9}$/;
      if (!re.test(mobile)) {
        this.$api.msg("手机号格式不正确");
        return;
      }
      this.$u.api
        .sendMobileCode({
          mobile: mobile,
          source: 6,
        })
        .then((res) => {
          // 发送验证码
          this.is_dis_yzm = !this.is_dis_yzm;
          const secondNumIn = setInterval(() => {
            this.num--;
            if (this.num === 0) {
              // 清除定时器
              clearInterval(secondNumIn);
              this.is_dis_yzm = false;
              this.num = 60;
            }
          }, 1000);
          this.$api.msg("发送成功");
        });
    },
    yzmLogin() {
      const mobile = this.$_utils.mobileRe(this.mobile);
      this.$u.api
        .smsLogin({
          mobile: mobile,
          smsCode: this.smsCode,
          source: this.$common.source(),
        })
        .then((data) => {
          uni.setStorageSync("token", data.data.token);
          uni.setStorageSync("expireTime", data.data.expireTime);
          // this.goPage(`/pages/index/index`, 'switchTab');
          // 更新登录状态
          this.$store.commit("commit_hasLogin", true);
          // 验证审核
          this.getCustomerInfo(data.data.token);
        });
    },
    H5WXLogin() {
      // #ifdef H5
      window.open(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf6aee42d157492f3&response_type=code&scope=snsapi_userinfo&redirect_uri=${encodeURIComponent(
          "https://devapi.dinghuomao.com/H5/#/pagesT/public/wxLogin"
        )}&state=123#wechat_redirect`
      );
      // #endif
    },
    loginFinish() {
      uni.switchTab({
        url: "/pages/user/user",
      });
    },
    WXLogin() {
      uni.getProvider({
        service: "oauth",
        success: (res) => {
          //支持微信、qq和微博等
          if (~res.provider.indexOf("weixin")) {
            uni.showLoading();
            uni.login({
              provider: "weixin",
              success: (loginRes) => {
                console.log(loginRes);
                // 获取用户信息
                uni.getUserInfo({
                  provider: "weixin",
                  success: (infoRes) => {
                    this.openId = infoRes.userInfo.openId;
                    // 用户图像
                    const avator = infoRes.userInfo.avatarUrl;
                    uni.setStorageSync("avator", avator);
                    // 用户昵称
                    const NickName = infoRes.userInfo.nickName;
                    uni.setStorageSync("NickName", NickName);
                    uni.setStorageSync("openid", infoRes.userInfo.openId);
                    if (!infoRes.userInfo.unionId) {
                      console.log(infoRes);
                      this.unionIDUserinfo(
                        loginRes.authResult.access_token,
                        infoRes.userInfo.openId
                      );
                    } else {
                      this.unionId = infoRes.userInfo.unionId;
                      uni.setStorageSync("unionid", infoRes.userInfo.unionId);
                      this.checkBindMiniProgram(
                        infoRes.userInfo.openId,
                        infoRes.userInfo.unionId
                      );
                    }
                    uni.hideLoading();
                    this.loginFinish();
                  },
                });
              },
            });
          }
        },
        complete: () => {
          // console.log('complete::getProvider');
        },
      });
    },
    // App微信授权登录获取unionID
    unionIDUserinfo(accessToken, openid) {
      // console.log('微信授权登录获取::', accessToken, openid);
      this.$u.api
        .unionIDUserinfo({
          access_token: accessToken,
          openid: openid,
          source: this.$common.source(),
        })
        .then(({ data }) => {
          // 用户图像
          const avator = data.headimgurl;
          uni.setStorageSync("avator", avator);
          // 用户昵称
          const NickName = data.nickname;
          uni.setStorageSync("NickName", NickName);
          // #ifdef APP-PLUS || MP
          this.unionId = data.unionId;
          uni.setStorageSync("unionid", data.unionId);
          // #endif
          // #ifdef H5
          this.unionId = data.unionid;
          // #endif
          this.checkBindMiniProgram(openid, this.unionId);
        });
    },
    // 判断是否已绑定  checkBindMiniProgram
    checkBindMiniProgram(openid, unionid) {
      this.$u.api
        .checkBindMiniProgram({
          openId: openid,
          unionId: unionid,
          source: this.$common.source(),
        })
        .then((data) => {
          uni.showToast({
            title: "是否已绑定成功",
            icon: "none",
            duration: 2000,
          });
          // 如果返回空绑定手机
          if (!data.data.token) {
            setTimeout(() => {
              this.goPage(`/pagesT/binding/bindPhone`);
            }, 100);
            return;
          } else {
            const token = data.data.token;
            uni.setStorageSync("token", token);
            uni.setStorageSync("expireTime", data.data.expireTime);
            // 更新登录状态
            this.$store.commit("commit_hasLogin", true);
            // 否则验证审核
            this.getCustomerInfo(data.data.token);
          }
        });
    },
    //先获取个人资料
    async getCustomerInfo(token) {
      this.$u.api.getCustomerInfo().then(({ data }) => {
        if (data.enableStatus === 4) {
          uni.clearStorageSync();
          uni.showModal({
            title: "账号已被禁用，您可以",
            content: "联系电话：" + (data.enterpriseMobile || ""),
            confirmText: "联系客服",
            cancelText: "取消",
            success: (res) => {
              if (res.confirm) {
                uni.makePhoneCall({
                  phoneNumber: data.enterpriseMobile,
                });
              } else {
              }
            },
          });
          return;
        }
        if (data.status === 3) {
          // uni.clearStorageSync();
          // 说明资料不完善，跳转到完善资料的页面
          uni.showModal({
            title: "审核未通过，请重新修改资料",
            content: data.auditFailReason || "",
            cancelText: "联系客服",
            confirmText: "修改资料",
            success: (res) => {
              if (res.confirm) {
                this.goPage("/pagesT/user/editUserInfo?token=" + token);
              } else if (res.cancel) {
                uni.makePhoneCall({
                  phoneNumber: data.enterpriseMobile,
                });
              }
            },
          });
        } else if (data.status === 1) {
          // uni.clearStorageSync();
          uni.showModal({
            title: "账号正在审核中，您可以",
            content: "联系电话：" + (data.enterpriseMobile || ""),
            confirmText: "先去逛逛",
            cancelText: "联系客服",
            success: (res) => {
              if (res.confirm) {
                this.goPage("/pages/index/index", "switchTab");
              } else {
                uni.makePhoneCall({
                  phoneNumber: data.enterpriseMobile,
                });
              }
            },
          });
        } else {
          // this.$emit('loginSuccess');
          this.goPage(`/pages/index/index`, "switchTab");
        }
      });
    },
  },
};
</script>
<style>
/* page不能写带scope的style标签中，否则无效 */
page {
  background: #ffffff;
}

.input-pl {
  color: #b8c0c8 !important;
}
</style>

<style lang="scss" scoped>
.box {
  .top-bg {
    width: 385rpx;
    height: 385rpx;
    background: linear-gradient(315deg, #fa6400 6%, #b620e0 49%, #32c5ff 88%);
    opacity: 0.08;
    filter: blur(50px);
    position: fixed;
    top: 20rpx;
    left: 0;
    z-index: 0;
  }

  .welcome-title {
    position: fixed;
    top: 162rpx;
    left: 56rpx;
    font-weight: bold;
    z-index: 1;
    line-height: 80rpx;
    font-size: 46rpx;
    font-family: jiangxikaiti;
  }

  .logo-img {
    position: fixed;
    top: 150rpx;
    right: 56rpx;

    image {
      width: 120rpx;
      border-radius: 34rpx;
      height: 120rpx;
      display: block;
      box-shadow: 0px 0px 20rpx 8rpx rgba(250, 100, 0, 0.08);
    }
  }

  .login-bg {
    position: fixed;
    top: 370rpx;
    left: 0;
    width: 100%;

    image {
      width: 360rpx;
      height: 360rpx;
      display: block;
      margin: 0 auto;
    }

    .login-btn-view {
      width: 638rpx;
      margin: 0 auto;

      .wx-Btn {
        margin-top: 106rpx;
        width: 638rpx;
        height: 89rpx;
        background: #fa6400;
        border-radius: 11rpx;
        line-height: 89rpx;
        text-align: center;
        font-weight: 500;
        color: #ffffff;
      }

      .yzm-Btn {
        margin-top: 40rpx;
        text-align: center;
        width: 638rpx;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 11rpx;
        border: 1px solid #cad0d7;
        color: #2d405e;
        font-size: 26rpx;

        .ibonshouji1 {
          font-size: 26rpx;
          margin-right: 14rpx;
        }
      }
    }

    .tab-ul {
      display: flex;
      padding: 0 56rpx;

      .tab-li {
        width: 328rpx;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 16rpx;
        color: #fa6400;
        text-align: center;
        background: linear-gradient(
            -62deg,
            transparent 32rpx,
            rgba(250, 100, 0, 0.08) 0
          )
          top right;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        margin-right: 40rpx;
      }

      .tab-on {
        width: 328rpx;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 16rpx;
        text-align: center;
        color: #ffffff;
        font-weight: 500;
        background: linear-gradient(117deg, transparent 32rpx, #fa6400 0) top
          left;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        margin-left: -25px;
      }
    }

    .input-ul {
      padding: 16rpx 0;

      .input-li {
        color: #2d405e;
        width: 638rpx;
        margin: 40rpx auto;
        height: 80rpx;
        background: #f5f5f6;
        border-radius: 4rpx;
        position: relative;
        padding-left: 88rpx;

        .ibonfont {
          position: absolute;
          font-size: 40rpx;
          top: 50%;
          transform: translateY(-50%);
          left: 24rpx;
        }

        input {
          color: #2d405e;
          height: 80rpx;
          line-height: 80rpx;
          width: 400rpx;
        }

        .yzm-view {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          right: 32rpx;
          color: #fa6400;
        }
      }
    }

    .login-btn {
      margin: 0 auto 170rpx;
      width: 638rpx;
      height: 89rpx;
      background: #fa6400;
      border-radius: 11rpx;
      line-height: 89rpx;
      text-align: center;
      font-weight: 500;
      color: #ffffff;
    }

    .divider-text {
      margin: 0 27rpx;
    }

    .wx-change-btn {
      color: #2d405e;
      margin: 50rpx auto 0;
      width: 638rpx;
      font-size: 26rpx;
      height: 80rpx;
      border-radius: 11rpx;
      line-height: 80rpx;
      text-align: center;
      border: 1px solid #cad0d7;

      .wxicon {
        vertical-align: middle;
        margin-right: 10rpx;
      }
    }
  }
}
</style>
